<template>
  <div>
    <el-drawer
      custom-class="wxkj-drawer"
      :title="'邀请' + name + '入职'"
      :before-close="drawerClose"
      :visible.sync="drawerShow"
      size="500"
    >
      <div class="drawer-content">
        <div class="ml20 mb20">
          <el-checkbox
            v-model="form.emailFlag"
          >同时向<span v-html="name" />发送邮件通知</el-checkbox>
        </div>
        <div class="ml20 mb20">应聘职位：{{ jobName }}</div>
        <el-form
          ref="form"
          :model="form"
          :rules="formRules"
          label-width="120px"
        >
          <el-form-item label="入职时间：" required prop="time">
            <el-date-picker
              v-model="form.time"
              type="datetime"
              :picker-options="pickerOptions"
              placeholder="选择日期"
              class="width100"
            />
          </el-form-item>

          <el-form-item label="联系人：" required prop="contactId">
            <el-col :span="16" class="mr5">
              <el-select
                v-model="form.contactId"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in contactList"
                  :key="item.id"
                  :label="item.userName"
                  :value="item.id"
                />
              </el-select>
            </el-col>
            <el-col :span="2" class="mr5 link-type">
              <span @click="showContactsDialog(null)">新增</span>
            </el-col>
            <el-col v-if="form.contactId" :span="2" class="mr5 link-type">
              <span @click="showContactsDialog(form.contactId)">编辑</span>
            </el-col>
            <el-col v-if="form.contactId" :span="2" class="mr5 link-type">
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                title="确定要删除此联系人吗？"
                @onConfirm="delContact"
              >
                <span slot="reference">删除</span>
              </el-popconfirm>
            </el-col>
          </el-form-item>

          <el-form-item label="备注信息：">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请填写备注信息"
            />
          </el-form-item>
          <el-form-item label="抄送同事：">
            <el-select
              v-model="form.peopleIds"
              multiple
              filterable
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in peopleList"
                :key="item.id"
                :label="item.name"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>

          <el-form-item v-loading="upload.loading" label="附件：">
            <span>{{ upload.name }}</span>
            <el-upload
              action="#"
              :multiple="false"
              :http-request="uploadRequest"
              :show-file-list="false"
            >
              <el-tooltip
                class="item"
                effect="dark"
                content="支持压缩包、PDF、word、excel，且仅能上传一个"
                placement="bottom"
              >
                <el-button type="text" class="link-type">上传</el-button>
              </el-tooltip>
            </el-upload>
          </el-form-item>
          <el-form-item class="fr">
            <el-button @click="drawerClose">取消</el-button>
            <el-button type="primary" :loading="submitLoading" @click="submitForm">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

    <colleague ref="colleague" />
    <contacts ref="contacts" type="录用" @refresh="getcontactList" />
  </div>
</template>

<script>
import colleague from './dialog/colleague'
import contacts from './dialog/contacts'
import { uploadFile } from '@/api/common'
import { list } from '@/api/colleague'
import { listContacts, delContacts, employment, editState } from '@/api/personnel'
export default {
  components: { colleague, contacts },
  data() {
    return {
      drawerShow: false,
      jobName: '',
      name: '',
      dataId: '',
      peopleList: [],
      submitLoading: false,
      form: {
        companyId: '',
        userId: '',
        jobId: '',
        time: '',
        contactId: '',
        remark: '',
        peopleIds: '',
        enclosureId: '',
        emailFlag: false
      },
      upload: {
        name: '',
        loading: false
      },
      formRules: {
        time: [{ required: true, message: '请选择入职时间' }],
        contactId: [{ required: true, message: '请选择联系人' }]
      },
      pickerOptions: {
        disabledDate: time => {
          return time.getTime() < Date.now()
        }
      },
      contactList: [], // 联系人列表
      contactsInfo: {} // 选中的联系人信息
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 销毁
  destroyed() {},
  // 方法
  methods: {
    // 上传附件
    uploadRequest(e) {
      const fileName = e.file.name
      const type = fileName.split('.').pop().toLowerCase()
      const isJPG = type === 'pdf' || type === 'xlsx' || type === 'docx' || type === 'xls' || type === 'doc' || type === 'zip'
      this.upload.loading = true
      if (!isJPG) {
        this.$message.error('上传格式不正确!')
        this.upload.loading = false
      } else {
        const formData = new FormData()
        formData.append('file', e.file)
        const date = new Date()
        formData.append('biz', 'public/position/' + date.getFullYear() + '/' + parseInt(date.getMonth() + 1))
        uploadFile(formData).then((res) => {
          this.form.enclosureId = res.result.fileId
          this.upload = {
            name: res.result.name,
            loading: false
          }
        }).catch(res => {
          this.upload = {
            name: '',
            loading: false
          }
        })
      }
    },
    // 联系人信息列表
    getcontactList() {
      listContacts({
        companyId: this.form.companyId,
        pageSize: 1000
      }).then((res) => {
        this.contactList = res.result.records
      })
    },
    // 显示
    show(name, userId, jobId, companyId, dataId, jobName) {
      this.dataId = dataId
      this.name = name
      this.form.userId = userId
      this.form.jobId = jobId
      this.jobName = jobName
      this.form.companyId = companyId
      this.getcontactList()
      this.drawerShow = true
      list(
        {
          pageSize: 10000,
          pageNo: 1
        }
      ).then(res => {
        this.peopleList = res.result.records
      })
    },
    // 打开同事信息弹窗
    showColleagueDialog(id) {
      this.$refs.colleague.show('1')
    },
    // 打开联系人弹窗
    showContactsDialog(id) {
      this.$refs.contacts.show(id, this.form.companyId)
    },

    // 删除联系人
    delContact() {
      delContacts({
        id: this.form.contactId
      }).then((res) => {
        this.form.contactId = ''
        this.getcontactList()
      })
    },
    drawerClose() {
      this.submitLoading = false
      this.$nextTick(() => {
        this.form = {
          companyId: '',
          userId: '',
          jobId: '',
          time: '',
          contactId: '',
          remark: '',
          peopleIds: '',
          enclosureId: '',
          emailFlag: false
        }
        this.upload = {
          name: '',
          loading: false
        }
        this.$refs.form.resetFields()
      })
      this.drawerShow = false
      this.$emit('refresh')
    },
    // 提交
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          const form = JSON.parse(JSON.stringify(this.form))
          if (form.peopleIds) {
            form.peopleIds = form.peopleIds.join(',')
          }
          employment(form).then((res) => {
            editState(
              {
                dataId: this.dataId,
                state: 5
              }
            ).then(res => {
              this.$message({
                message: 'offer发送成功',
                type: 'success'
              })
              this.submitLoading = false
              this.drawerClose()
            }).catch(err => {
              this.submitLoading = false
            })
          }).catch(err => {
            this.submitLoading = false
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
